package com.bdtop.dbl.ui.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.R;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
public class WapActivity extends BaseActivity {

	private WebView webView;

	public static void launch(Context context, String url, String title) {
		Intent intent = new Intent(context, WapActivity.class);
		intent.putExtra(Constants.BUNDLE_URL, url);
		intent.putExtra("wap_title", title);
		context.startActivity(intent);
	}

	@SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_wap);
		super.onCreate(savedInstanceState);

		String title = getIntent().getStringExtra("wap_title");
		mTitleBar.setTitle(title);

		webView = (WebView) this.findViewById(R.id.webview);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setRenderPriority(RenderPriority.HIGH);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.setInitialScale(8);
		
		// webView.addJavascriptInterface(new WebAppInterface(this), "Android");
		// webView.addJavascriptInterface(new Handler(), "app");
		webView.loadData("", "text/html", null);
		webView.setWebViewClient(viewClient);
		webView.setWebChromeClient(chromeClient);

		String url = getIntent().getStringExtra(Constants.BUNDLE_URL);
		if (TextUtils.isEmpty(url)) {
			showToast("null url!");
			finish();
		}
		webView.loadUrl(url);

		webView.getSettings().setAppCacheEnabled(true);
	}

	private WebChromeClient chromeClient = new WebChromeClient() {

		@Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

				builder.setTitle("对话框").setMessage(message).setPositiveButton("确定", null);

				// 不需要绑定按键事件
				// 屏蔽keycode等于84之类的按键
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
				result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
			} catch (Exception e) {
				DBLDebug.loge("wap on js alert : activity die ? ~");
			}

			return true;
			// return super.onJsAlert(view, url, message, result);
		}

		@Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				builder.setTitle("对话框").setMessage(message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});
				builder.setOnCancelListener(new OnCancelListener() {
					@Override public void onCancel(DialogInterface dialog) {
						result.cancel();
					}
				});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					@Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsConfirm", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
			} catch (Exception e) {

				DBLDebug.loge("wap on js alert : activity die ? ~");
			}
			return true;
			// return super.onJsConfirm(view, url, message, result);
		}

		@Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

				builder.setTitle("对话框").setMessage(message);

				final EditText et = new EditText(view.getContext());
				et.setSingleLine();
				et.setText(defaultValue);
				builder.setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.confirm(et.getText().toString());
					}

				}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsPrompt", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});

				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
			} catch (Exception e) {
				DBLDebug.loge("wap on js alert : activity die ? ~");
			}
			return true;
			// return super.onJsPrompt(view, url, message, defaultValue,
			// result);
		}
	};

	private WebViewClient viewClient = new WebViewClient() {
		@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// view.loadUrl(url);
			// return true;
			return false;
		}

		@Override public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
		}

		@Override public void onPageFinished(WebView view, String url) {
		}
	};

	@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (webGoBack())
				return true;
		}
		// If it wasn't the Back key or there's no web page history, bubble up
		// to the default
		// system behavior (probably exit the activity)
		return super.onKeyDown(keyCode, event);
	}

	public OnClickListener onBackClickListener = new OnClickListener() {
		@Override public void onClick(View view) {

			if (!webGoBack()) {
				finish();
			}
		}
	};

	private boolean webGoBack() {
		if (webView.canGoBack()) {
			webView.goBack();
			return true;
		}
		return false;
	}
}
